package com.github.tvbox.osc.ui.activity;

import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.TextView;

import com.github.tvbox.osc.R;
import com.github.tvbox.osc.ui.adapter.AdapterProvider;
import com.github.tvbox.osc.ui.adapter.SortAdapter;
import com.github.tvbox.osc.ui.dialog.SiteDialog;
import com.github.tvbox.osc.ui.fragment.GridFragmentKt;
import com.owen.tvrecyclerview.widget.TvRecyclerView;
import com.owen.tvrecyclerview.widget.V7LinearLayoutManager;

import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import io.github.source.media.bean.MediaCategory;
import me.jessyan.autosize.utils.AutoSizeUtils;

/**
 * @ClassName: HomeMediaCategory
 * @Description: (分类标签)管理
 * @author: huangrongcai
 * @date: 2024/6/27
 * @Copyright: 黄嵘才（HuangRc)
 */
public class MediaCategoryManager {/*接口化*/
    private boolean initViewed = false;
    private final WeakHashMap<View, Boolean> viewStates = new WeakHashMap<>();
    private final List<MediaCategory> data = new ArrayList<>();
    private RecyclerView mGridView;
    private SortAdapter sortAdapter;
    private FragmentManager mFragmentManager;
    private final Lifecycle mLifecycle;
    private int currentSelected = 0;
    private int sortFocused = 0;

    private boolean isDownOrUp = false;
    private boolean sortChange = false;
    private View sortFocusView = null;
    private final Handler mHandler = new Handler();

    public static MediaCategoryManager create(@NonNull FragmentActivity fActivity, View view) {
        MediaCategoryManager manager = new MediaCategoryManager(fActivity);
        manager.setView(view);
        return manager;
    }

    public static MediaCategoryManager create(@NonNull Fragment fragment, View view) {
        MediaCategoryManager manager = new MediaCategoryManager(fragment);
        manager.setView(view);
        return manager;
    }

    public MediaCategoryManager(@NonNull FragmentActivity fragmentActivity) {
        this(fragmentActivity.getSupportFragmentManager(), fragmentActivity.getLifecycle());
    }

    public MediaCategoryManager(@NonNull Fragment fragment) {
        this(fragment.getChildFragmentManager(), fragment.getLifecycle());
    }

    public MediaCategoryManager(@NonNull FragmentManager fragmentManager,
                                @NonNull Lifecycle lifecycle) {
        mFragmentManager = fragmentManager;
        mLifecycle = lifecycle;
    }

    public void setView(View view) {
        if (view instanceof RecyclerView) {
            mGridView = (RecyclerView) view;
        } else {
            mGridView = null;
        }
    }

    public void onChangedToSelect(int position) {
        //页面选中》选项卡选中
        sortAdapter.notifyItemChanged(sortAdapter.selected);
        sortAdapter.selected = position;
        sortAdapter.notifyItemChanged(position);
    }


    public MediaCategoryManager initView() {
        if (!initViewed) {
            initRecyclerView();
        }
        return this;
    }

    private void initRecyclerView() {
        if (this.sortAdapter == null) {
            this.sortAdapter = AdapterProvider.with().getHomeSortAdapter();
        }
        mGridView.setLayoutManager(new V7LinearLayoutManager(context(), 0, false));
        if (mGridView instanceof TvRecyclerView) {
            ((TvRecyclerView) mGridView).setSpacingWithMargins(0, AutoSizeUtils.dp2px(context(), 10.0f));
            ((TvRecyclerView) mGridView).setOnItemListener(new ItemClickListener());
            ((TvRecyclerView) mGridView).setOnInBorderKeyEventListener(new InBorderKeyEventListener());
        }
        mGridView.setAdapter(this.sortAdapter);

        initViewed = true;
    }

    private void handleViewAnimation(View view, boolean isSelected) {
        if (view != null) {
            float scaleX = isSelected ? 1.1f : 1.0f;
            float scaleY = scaleX;
            int textColor = isSelected ? R.color.color_FFFFFF : R.color.color_BBFFFFFF;
            boolean isBold = isSelected;

            view.animate().scaleX(scaleX).scaleY(scaleY).setInterpolator(new BounceInterpolator()).setDuration(300).start();
            TextView textView = view.findViewById(R.id.tvTitle);
            textView.getPaint().setFakeBoldText(isBold);
            textView.setTextColor(context().getResources().getColor(textColor));
            textView.postInvalidate();
            if (sortAdapter.getItem(sortFocused) == null) {
                view.findViewById(R.id.tvFilter).setVisibility(View.GONE);

            } else {
                view.findViewById(R.id.tvFilter).setVisibility(isSelected && !sortAdapter.getItem(sortFocused).getFilters().isEmpty() ? View.VISIBLE : View.GONE);
            }
        }
    }

    public void handleOnItemClick(MediaCategory item, int position) {
        // 非空校验
        if (item == null || mClickedListener == null || context() == null) {
            // 根据具体情况，可以选择记录日志、抛出异常或者进行其他处理
            return;
        }
        try {
            if (currentSelected == 0/*0代表第一个标签*/) {
                SiteDialog.create(context()).show();
            } else {
                sortAdapter.selected = position;
                mClickedListener.onItemClicked(item, position);

            }
        } catch (Exception e) {
            // 异常处理逻辑，例如记录日志、提示用户错误信息等
            e.printStackTrace();
        }

    }

    /**
     * 设置数据
     *
     * @param data 数据
     */
    public void setNewData(@Nullable List<MediaCategory> data) {
        this.data.clear();
        this.data.addAll(data != null ? data : new ArrayList<>());

        initView();
        sortAdapter.setNewData(this.data);
    }

    public List<MediaCategory> getData() {
        return sortAdapter.getData();
    }

    public int getSize() {
        return getData().size();
    }

    private final Runnable mDataRunnable = () -> {
        try {
            processCategoryChange();
        } catch (Exception e) {
            // 根据实际情况处理异常，例如记录日志等
            e.printStackTrace();
        }
    };

    private void processCategoryChange() {
        if (sortChange) {
            sortChange = false;
            if (sortFocused != currentSelected && mStateListener != null) {
                currentSelected = sortFocused;
                mStateListener.onItemSelected(sortFocused);
            }
        }
    }

    private Context context() {
        return mGridView.getContext();
    }

    public int getCurrentSelected() {
        return currentSelected;
    }

    private StateListener mStateListener;

    public MediaCategoryManager setStateListener(StateListener listener) {
        mStateListener = listener;
        return this;
    }

    private ClickedListener mClickedListener;

    public MediaCategoryManager setClickedListener(ClickedListener listener) {
        mClickedListener = listener;
        return this;
    }

    private OnInBorderKeyEventListener mOnInBorderKeyEventListener;

    public MediaCategoryManager setOnInBorderKeyEventListener(OnInBorderKeyEventListener listener) {
        mOnInBorderKeyEventListener = listener;
        return this;
    }

    public interface StateListener {
        void onItemSelected(int position);
    }

    public interface ClickedListener {
        void onItemClicked(MediaCategory item, int position);
    }

    public interface OnInBorderKeyEventListener {
        boolean onInBorderKeyEvent(int direction, View focused);
    }

    private class ItemClickListener implements TvRecyclerView.OnItemListener {
        @Override
        public void onItemPreSelected(TvRecyclerView tvRecyclerView, View view, int position) {
            handleViewAnimation(view, false);
            viewStates.put(view, false);
        }

        @Override
        public void onItemSelected(TvRecyclerView tvRecyclerView, View view, int position) {
            isDownOrUp = false;
            sortChange = true;
            handleViewAnimation(view, true);
            viewStates.put(view, true);

            sortFocusView = view;
            sortFocused = position;
            mHandler.removeCallbacks(mDataRunnable);
            mHandler.postDelayed(mDataRunnable, 10);
            if (!sortAdapter.getItem(position).getFilters().isEmpty())
                view.findViewById(R.id.tvFilter).setVisibility(View.VISIBLE);

        }

        @Override
        public void onItemClick(TvRecyclerView parent, View itemView, int position) {
            if (itemView != null && currentSelected == position) {
                handleOnItemClick(sortAdapter.getItem(position), position);
            }
        }
    }

    private class InBorderKeyEventListener implements TvRecyclerView.OnInBorderKeyEventListener {
        @Override
        public final boolean onInBorderKeyEvent(int direction, View view) {
            return mOnInBorderKeyEventListener.onInBorderKeyEvent(direction, view);
        }
    }

    /**
     * 管理两者的互动交互关系
     */
    public static class TabMediator {
        private final MediaCategoryManager categoryManager;
        //更新时间
        //ViewPager
        private final ViewPagerManager viewPagerManager;
        private final ClickedListener listener;
        private int sortFocused = 0;

        /**
         * @param category
         * @param viewPager
         * @param listener  点击选中
         */
        public TabMediator(MediaCategoryManager category, ViewPagerManager viewPager, ClickedListener listener) {
            this.categoryManager = category;
            this.viewPagerManager = viewPager;
            this.listener = listener;
        }

        public void attach() {
            categoryManager.setClickedListener((item, position) -> {
                if (categoryManager.getCurrentSelected() == 0) {
                    SiteDialog.create(categoryManager.context()).show();
                } else {
                    updateFilter(item);
                }
            });
            categoryManager.setStateListener(position -> {
                viewPagerManager.setCurrentItem(position);
                listener.onItemClicked(categoryManager.data.get(position), position);
                sortFocused = position;
            });
            categoryManager.setOnInBorderKeyEventListener((direction, focused) -> {
                if (direction != View.FOCUS_DOWN) {
                    return false;
                }
                Fragment fragment = viewPagerManager.getFragment(sortFocused);
                if (!(fragment instanceof GridFragmentKt)) {
                    return false;
                }
                if (!((GridFragmentKt) fragment).isLoad()) {
                    return true;
                }
                return false;
            });
            viewPagerManager.setOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    categoryManager.onChangedToSelect(position);

                }
            });
        }

        private void updateFilter(MediaCategory item) {
            if (getFragment() == null) return;
            getFragment().showFilter();
        }

        private GridFragmentKt getFragment() {
            Fragment fragment = viewPagerManager.getFragment(categoryManager.getCurrentSelected());
            if ((fragment instanceof GridFragmentKt)) {
                return ((GridFragmentKt) fragment);
            }
            return null;
        }
    }
}
